import React, { useMemo } from 'react';
import { Dropdown, Menu, Space } from 'antd';
import { UserOutlined, DownOutlined, IdcardOutlined, ClockCircleOutlined, LogoutOutlined } from '@ant-design/icons';
import './index.scss';

const UserInfo = ({ userInfo, onLogout }) => {
  const formatLoginTime = useMemo(() => {
    if (!userInfo.loginTime) return '';
    const date = new Date(userInfo.loginTime);
    return date.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  }, [userInfo.loginTime]);

  const handleMenuClick = ({ key }) => {
    if (key === 'logout') {
      onLogout();
    }
  };

  const menu = (
    <Menu onClick={handleMenuClick}>
      <Menu.Item key="username" icon={<UserOutlined />}>
        用户：{userInfo.username}
      </Menu.Item>
      {userInfo.role === 'admin' && (
        <Menu.Item key="admin-role" icon={<IdcardOutlined />}>
          管理员身份
        </Menu.Item>
      )}
      <Menu.Item key="login-time" icon={<ClockCircleOutlined />}>
        登录时间：{formatLoginTime}
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout" icon={<LogoutOutlined />}>
        退出登录
      </Menu.Item>
    </Menu>
  );

  return (
    <div className="user-info-container">
      <Dropdown overlay={menu} trigger={['hover']}>
        <div className="user-avatar-antd">
          <Space>
            <div className="avatar-icon-antd">
              <UserOutlined />
            </div>
            <span className="username-antd">{userInfo.username}</span>
            <DownOutlined />
          </Space>
        </div>
      </Dropdown>
    </div>
  );
};

export default UserInfo;